
import asyncio
import aiofiles
from argparse import ArgumentParser
import configparser
import glob
import pathlib
import pandas as pd
from loguru import logger
from tqdm import tqdm
from typing import List, Dict, NewType, TypedDict
import os

async def calculate_frequency(args: dict):
    folder = args['folder']
    result = {}
    for file in tqdm(glob.glob(f'{folder}/*.ini')):
        async with aiofiles.open(file, mode='r') as f:
            content = await f.read()
            parser = configparser.ConfigParser(strict=False)
            parser.read_string(content)
            for section in parser.sections():
                if not section.startswith('PACENOTES'):
                    # now it's a pacenote call
                    if parser[section].get('type'):
                        _type = int(parser[section]['type'])
                        if _type not in result:
                            result[_type] = 0
                        result[_type] += 1

    return result
    pass

async def main():

    OUTPUT_PATH = pathlib.Path('out')
    parser = ArgumentParser()
    parser.add_argument('-f', '--folder', help='RBR pacenote folder with ini files')
    args = parser.parse_args()
    args = vars(args)

    frequency = await calculate_frequency(args)
    t = pd.Series(frequency)

    rbr_pacenote = pd.read_csv(OUTPUT_PATH / 'Rbr.csv')

    t = pd.DataFrame(t, columns=['Frequency'])
    t['Id'] = t.index
    t = t.merge(rbr_pacenote, how='left', left_on="Id", right_on="Id")

    OUTPUT_PATH = OUTPUT_PATH / 'rbr_pacenote_frequency'
    OUTPUT_PATH.mkdir(parents=True, exist_ok=True)
    t = t.sort_values(by='Frequency', ascending=False)
    t.to_csv(OUTPUT_PATH / 'frequency.csv')
    pass

if __name__ == '__main__':
    asyncio.run(main())
